package cn.virens.common.project.generator.database.beetl;

import cn.virens.common.util.exception.APIException;
import com.mysql.cj.jdbc.DatabaseMetaData;
import org.beetl.core.Format;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.reflect.FieldUtil;
import org.dromara.hutool.core.text.CharSequenceUtil;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class BeetlFtKeyword implements Format {
    private final Set<String> keyword;

    public BeetlFtKeyword() throws APIException {
        this.keyword = new HashSet<>(getMeta("SQL2003_KEYWORDS"));

        for (String key : (String[]) getMeta("MYSQL_KEYWORDS")) {
            this.keyword.add(key);
        }
    }

    @Override
    public Object format(Object data, String pattern) {
        if (data instanceof CharSequence) {
            return str(data.toString());
        } else {
            return data;
        }
    }

    private String str(String str) throws APIException {
        if (str != null && contains(keyword, str)) {
            return "`" + str + "`";
        } else {
            return str;
        }
    }

    private static <T> T getMeta(String field) throws APIException {
        return getFieldValue(DatabaseMetaData.class, field);
    }

    @SuppressWarnings("unchecked")
    private static <T> T getFieldValue(Class<?> clazz, String field) throws APIException {
        return (T) FieldUtil.getFieldValue(null, FieldUtil.getField(clazz, field));
    }

    private static boolean contains(Collection<String> coll, String str) throws APIException {
        return CollUtil.contains(coll, item -> CharSequenceUtil.equalsIgnoreCase(item, str));
    }
}
